<template>
  <Upload
    :action="uploadFileUrl"
    :data="data"
    :headers="headers"
    :disabled="disabled"
    v-model="fileList"
    @error="onError"
    @success="onSuccess"
    name="file"
    method="post"
    @progress="onProgress"
    @beforeUpload="beforeUpload"
    @start="onStart"
    listType="text"
    @updateModelValue="handleChange"
    @remove="remove"
    @click="onClick"
    :removeFile="removeFile"
    :multiple="multiple"
    :accept="fileType.join(',')"
  >
    <template v-slot:description>
      <div v-if="showTip">
        请上传
        <template v-if="fileSize">
          大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b>
        </template>
        <template v-if="fileType">
          格式为 <b style="color: #f56c6c">{{ fileType.join("/") }}</b>
        </template>
        的文件
      </div>
    </template>
  </Upload>
</template>

<script>
import { getToken } from "@/utils/auth";
import { Message } from "@uni/vue";
import request from "@/utils/request";
export default {
  props: {
    value: [String, Object, Array],
    // 大小限制(MB)
    fileSize: {
      type: Number,
      default: 5,
    },
    multiple: {
      type: Boolean,
      default: true,
    },
    // 数量限制
    limit: {
      type: Number,
      default: 5,
    },
    // 文件类型, 例如['png', 'jpg', 'jpeg']
    fileType: {
      type: Array,
      default: () => ["doc", "docx", "xls", "ppt", "pdf"],
    },
    // 是否显示提示
    isShowTip: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {
      baseUrl: process.env.VUE_APP_BASE_API,
      uploadFileUrl: process.env.VUE_APP_BASE_API + "/common/upload", // 上传的图片服务器地址
      data: {},
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      disabled: false,
      fileList: [],
      uploadList: [],
      removeFile: false
    };
  },
  watch: {
    value: {
      handler(val) {
        if (val) {
          let temp = 1;
          // 首先将值转为数组
          const list = Array.isArray(val) ? val : this.value.split(",");
          // 然后将数组转为对象数组
          this.fileList = list.map((item) => {
            if (typeof item === "string") {
              item = {
                name: this.getFileName(item),
                url: item,
                newName: item,
              };
            }
            item.uuid = item.uuid || new Date().getTime() + temp++;
            item.thumbUrl = "";
            item.status = "done";
            item.percent = "";
            return item;
          });
          this.uploadList = this.fileList;
        } else {
          this.fileList = [];
          this.uploadList = [];
          return [];
        }
      },
      deep: true,
      immediate: true,
    },
  },
  computed: {
    // 是否显示提示
    showTip() {
      return this.isShowTip && (this.fileType || this.fileSize);
    },
  },
  methods: {
    // 获取文件名称
    getFileName(name) {
      if (name.lastIndexOf("/") > -1) {
        return (
          name.slice(name.lastIndexOf("/") + 1, name.lastIndexOf("_")) +
          (name.lastIndexOf(".") > 0
            ? name.slice(name.lastIndexOf("."), name.length)
            : name.slice(name.lastIndexOf("_") + 1))
        );
      } else {
        return name;
      }
    },
    onError(e) {
      console.log("e", onError);
    },
    onClick(file,evt) {
      if(file.url){
      let href = document.createElement('a')
      href.setAttribute('href', `${this.baseUrl}${file.url}`)
      href.setAttribute('target', '_blank')
      href.click()
      // window.open( `${this.baseUrl}${file.url}`)
      }

    },
    onSuccess(res, r) {
      this.uploadList.push({
        name: res.originalFilename,
        url: res.fileName,
        newName: res.fileName,
      });
      this.$emit("input", this.listToString(this.uploadList));

    },
    // 对象转成指定字符串分隔
    listToString(list, separator) {
      let strs = "";
      separator = separator || ",";
      for (let i in list) {
        strs += list[i].url + separator;
      }
      return strs != "" ? strs.substr(0, strs.length - 1) : "";
    },
    beforeUpload(file, files, callback) {
       // 校检文件数量
      if(this.uploadList.length==this.limit) {
          Message.error({ text: `上传文件数量不能超过${this.limit}个!` });
          this.fileList = this.fileList.filter((item)=>item.status!='uploading')
          
          return callback(false);
      }
      // 校检文件类型
      if (this.fileType) {
        let fileExtension = "";
        if (file.name.lastIndexOf(".") > -1) {
          fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
        }
        const isTypeOk = this.fileType.some((type) => {
          if (file.type.indexOf(type) > -1) return true;
          if (fileExtension && fileExtension.indexOf(type) > -1) return true;
          return false;
        });
        if (!isTypeOk) {
          Message.error({
            text: `文件格式不正确, 请上传${this.fileType.join("/")}格式文件!`,
          });
          return callback(false);
        }
      }
      // 校检文件大小
      if (this.fileSize) {
        const isLt = file.size / 1024 / 1024 < this.fileSize;
        if (!isLt) {
          Message.error({ text: `上传文件大小不能超过 ${this.fileSize} MB!` });
          return callback(false);
        }
      }
      return callback(file);
    },
    onProgress(a, b) {
      console.log("onProgress", a, b);
    },
    onStart(file) {
      if (!file[0].transformedFile) {
        console.log("fileList:", this.fileList);
      }
    },
    handleChange(files) {
      console.log('fileList:', this.fileList)
      this.uploadList.map((item, index) => {
        files.map((file, fileIndex) => {
          if (index == fileIndex) {
            item.uuid = file.uuid;
            item.thumbUrl = file.thumbUrl;
            item.status = file.status;
            item.percent = file.percent;
          }
        });
      });
    },
    remove(file, evt) {
      if(file.status == "uploading") {
        this.fileList = this.fileList.filter((item)=>item.uuid !== file.uuid)
        return
      }
      let index = this.fileList.findIndex((el) => {
        return el.uuid === file.uuid;
      });
      let delFile = this.uploadList[index];
      this.$MessageBox.ModalConfirm(
        '是否确认删除名称为"' + file.name + '"的文件？',
        () => {
          this.handleDelete(delFile, index);
        }
      );
    },
    // 删除文件
    handleDelete(file, index) {
      return request({
        url: "/common/defile/",
        method: "delete",
        params: {
          file: file.newName.replace("/profile/upload", ""),
        },
      }).then((response) => {
        if (response.bool) {
          this.uploadList.splice(index, 1);
          this.$emit("input", this.listToString(this.uploadList));
          Message.success({ text: `删除成功` });
        } else {
        }
      });
    },
  },
};
</script>
<style>

</style>